#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
林氏整装定制 - Gitee API 上传脚本
用于自动化上传项目文件到Gitee仓库
"""

import requests
import base64
import json
import os
import sys

class GiteeUploader:
    def __init__(self, username, access_token, repo_name="linsy-custom-homepage"):
        self.username = username
        self.access_token = access_token
        self.repo_name = repo_name
        self.base_url = f"https://gitee.com/api/v5/repos/{username}/{repo_name}"
        
    def create_repo(self):
        """创建仓库"""
        print("📦 正在创建仓库...")
        url = "https://gitee.com/api/v5/user/repos"
        data = {
            "name": self.repo_name,
            "description": "林氏整装定制营销页面",
            "private": False,
            "has_issues": True,
            "has_wiki": True,
            "has_downloads": True
        }
        
        try:
            response = requests.post(
                url, 
                headers={"Authorization": f"token {self.access_token}"}, 
                json=data
            )
            
            if response.status_code == 201:
                print("✅ 仓库创建成功")
                return True
            elif response.status_code == 422:
                print("⚠️ 仓库可能已存在，继续上传文件...")
                return True
            else:
                print(f"❌ 仓库创建失败: {response.text}")
                return False
                
        except Exception as e:
            print(f"❌ 创建仓库出错: {str(e)}")
            return False
    
    def upload_file(self, filename):
        """上传单个文件"""
        try:
            # 检查文件是否存在
            if not os.path.exists(filename):
                print(f"⚠️ 文件不存在: {filename}")
                return False
            
            # 读取文件内容
            with open(filename, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # Base64编码
            content_b64 = base64.b64encode(content.encode('utf-8')).decode('utf-8')
            
            # 准备请求数据
            data = {
                "access_token": self.access_token,
                "content": content_b64,
                "message": f"添加{filename} - 林氏整装定制项目",
                "branch": "master"
            }
            
            # 发送请求
            response = requests.post(
                f"{self.base_url}/contents/{filename}",
                headers={"Content-Type": "application/json"},
                json=data
            )
            
            if response.status_code == 201:
                print(f"✅ {filename} 上传成功")
                return True
            elif response.status_code == 422:
                print(f"⚠️ {filename} 可能已存在，尝试更新...")
                return self.update_file(filename, content_b64)
            else:
                print(f"❌ {filename} 上传失败: {response.text}")
                return False
                
        except Exception as e:
            print(f"❌ {filename} 上传出错: {str(e)}")
            return False
    
    def update_file(self, filename, content_b64):
        """更新文件"""
        try:
            # 获取文件SHA
            response = requests.get(
                f"{self.base_url}/contents/{filename}",
                headers={"Authorization": f"token {self.access_token}"}
            )
            
            if response.status_code == 200:
                file_info = response.json()
                sha = file_info.get('sha')
                
                # 更新文件
                data = {
                    "access_token": self.access_token,
                    "content": content_b64,
                    "message": f"更新{filename} - 林氏整装定制项目",
                    "branch": "master",
                    "sha": sha
                }
                
                response = requests.put(
                    f"{self.base_url}/contents/{filename}",
                    headers={"Content-Type": "application/json"},
                    json=data
                )
                
                if response.status_code == 200:
                    print(f"✅ {filename} 更新成功")
                    return True
                else:
                    print(f"❌ {filename} 更新失败: {response.text}")
                    return False
            else:
                print(f"❌ 获取{filename}信息失败")
                return False
                
        except Exception as e:
            print(f"❌ {filename} 更新出错: {str(e)}")
            return False
    
    def enable_pages(self):
        """启用Gitee Pages"""
        print("🌐 正在启用Gitee Pages...")
        url = f"{self.base_url}/pages/builds"
        data = {"access_token": self.access_token}
        
        try:
            response = requests.post(
                url, 
                headers={"Authorization": f"token {self.access_token}"}, 
                json=data
            )
            
            if response.status_code == 201:
                print("✅ Gitee Pages 启用成功")
                return True
            else:
                print(f"❌ Gitee Pages 启用失败: {response.text}")
                return False
                
        except Exception as e:
            print(f"❌ 启用Gitee Pages出错: {str(e)}")
            return False
    
    def deploy(self):
        """完整部署流程"""
        print("🚀 开始部署林氏整装定制项目...")
        print("=" * 50)
        
        # 1. 创建仓库
        if not self.create_repo():
            print("❌ 仓库创建失败，部署终止")
            return False
        
        # 2. 上传文件
        files = ["index.html", "README.md", "deploy.md"]
        print(f"\n📤 开始上传 {len(files)} 个文件...")
        
        success_count = 0
        for filename in files:
            if self.upload_file(filename):
                success_count += 1
        
        print(f"\n📊 文件上传完成: {success_count}/{len(files)} 个文件成功")
        
        if success_count < len(files):
            print("⚠️ 部分文件上传失败，但继续启用Pages...")
        
        # 3. 启用Pages
        if self.enable_pages():
            print("\n🎉 部署完成！")
            print(f"🌐 访问地址: https://{self.username}.gitee.io/{self.repo_name}")
            print("⏰ 请等待1-2分钟让部署生效")
            print("\n📱 您可以将此链接分享给客户访问")
            return True
        else:
            print("\n❌ Gitee Pages 启用失败")
            print("💡 您可以手动在Gitee仓库设置中启用Pages")
            return False

def main():
    """主函数"""
    print("林氏整装定制 - Gitee API 上传工具")
    print("=" * 50)
    
    # 检查必要文件
    required_files = ["index.html", "README.md", "deploy.md"]
    missing_files = [f for f in required_files if not os.path.exists(f)]
    
    if missing_files:
        print(f"❌ 缺少必要文件: {', '.join(missing_files)}")
        print("请确保所有文件都在当前目录中")
        return
    
    # 获取用户输入
    print("请输入您的Gitee配置信息:")
    username = input("Gitee用户名: ").strip()
    access_token = input("访问令牌: ").strip()
    
    if not username or not access_token:
        print("❌ 用户名和访问令牌不能为空")
        return
    
    # 确认信息
    print(f"\n📋 配置信息确认:")
    print(f"用户名: {username}")
    print(f"仓库名: linsy-custom-homepage")
    print(f"令牌: {access_token[:8]}...")
    
    confirm = input("\n确认开始部署? (y/N): ").strip().lower()
    if confirm != 'y':
        print("部署已取消")
        return
    
    # 开始部署
    uploader = GiteeUploader(username, access_token)
    uploader.deploy()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n❌ 部署被用户中断")
    except Exception as e:
        print(f"\n❌ 部署过程中出现错误: {str(e)}")
        print("请检查网络连接和配置信息") 